package com.epfresh.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.epfresh.R;
import com.epfresh.adapter.MineAttentionViewBinder;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.bean.ContentEntity;
import com.epfresh.bean.ListStore;
import com.epfresh.global.BaseActivity;
import com.epfresh.views.MultiStateView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

import multitype.MultiTypeAdapter;
import multitype.loadmore.LoadMoreDelegate;
import multitype.loadmore.LoadMoreItem;

public class MineAttentionActivity extends BaseActivity {
    private MultiStateView multi_state;
    private MultiTypeAdapter multiAdapter;
    private List<Object> items = new ArrayList<>();
    private PtrFrameLayout ptrFrameLayout;
    private RecyclerView rv_store_list;
    private LoadMoreDelegate loadMoreDelegate = new LoadMoreDelegate();

    private int pageNum = 0;
    private boolean isRefresh = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_attention);
        toolbarTitle.setText("我的关注");
        initView();
    }

    private void initView() {
        multi_state = findViewById(R.id.multi_state);
        ptrFrameLayout = findViewById(R.id.ptr_frame_layout);
        rv_store_list = findViewById(R.id.rv_store_list);
        multiAdapter = new MultiTypeAdapter();

        ptrFrameLayout.setPtrHandler(ptrHandler);
        loadMoreDelegate.attach(rv_store_list, loadMoreSubject);
        multi_state.setViewForState(R.layout.loading_view, MultiStateView.VIEW_STATE_LOADING);
        multi_state.setViewForState(R.layout.empty_view_no_store, MultiStateView.VIEW_STATE_EMPTY);

        MineAttentionViewBinder mineAttentionViewBinder = new MineAttentionViewBinder();
        mineAttentionViewBinder.setOnItemClickListener(new MineAttentionViewBinder.OnItemClickListener() {
            @Override
            public void onItemClick(ListStore item) {
                Intent storeIntent = new Intent(MineAttentionActivity.this, CommonStoreActivity.class);
                storeIntent.putExtra("storeId",item.getId());
                startActivity(storeIntent);
            }
        });
        multiAdapter.register(ListStore.class,mineAttentionViewBinder);
        multiAdapter.register(LoadMoreItem.class,loadMoreDelegate.getLoadMoreViewBinder());
        multiAdapter.setItems(items);

        rv_store_list.setLayoutManager(new LinearLayoutManager(MineAttentionActivity.this));
        rv_store_list.setAdapter(multiAdapter);
        refresh();
    }

    /**
     * 刷新
     */
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, rv_store_list, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    /**
     * 加载更多
     */
    private LoadMoreDelegate.LoadMoreSubject loadMoreSubject = new LoadMoreDelegate.LoadMoreSubject() {
        @Override
        public boolean canLoad() {
            return !ptrFrameLayout.isRefreshing();
        }

        @Override
        public void onLoadMore() {
            loadMoreDelegate.setStatusLoading();
            loadMore();
        }
    };

    private void refresh() {
        items.clear();
        pageNum = 0;
        reqStoreList();
    }

    private void loadMore() {
        pageNum += 1;
        reqStoreList();
    }

    private void reqStoreList() {
        RequestEntityMap requestEntityMap = new RequestEntityMap();
        requestEntityMap.setCmd(AppPurchaseRouterConstant.cmd_store_store_list);
        requestEntityMap.putParameter("sortProperty", "name");
        requestEntityMap.putParameter("favorite", "true");
        requestEntityMap.putParameter("pageNumber", pageNum);
        requestEntityMap.putParameter("pageSize", 10);
        requestEntityMap.putParameter("sortDirection", "DESC");

        request(requestEntityMap, AppPurchaseRouterConstant.cmd_store_store_list, new OnRequestListener<ContentEntity<ListStore>>() {
            @Override
            public ContentEntity<ListStore> jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, new TypeToken<ContentEntity<ListStore>>() {
                }.getType());
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                ptrFrameLayout.refreshComplete();
                multi_state.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                T.toast(failCode + "");
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                ptrFrameLayout.refreshComplete();
                multi_state.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                T.toast(failCode + "");
            }

            @Override
            public void onStart(Object tag) {
                if (!isRefresh){
                    multi_state.setViewState(MultiStateView.VIEW_STATE_LOADING);
                    isRefresh = true;
                }
            }

            @Override
            public void onResponse(ResponseEntity<ContentEntity<ListStore>> response, Object tag) {
                ptrFrameLayout.refreshComplete();
                multi_state.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                if (response.getResponseElement() != null) {
                    if (response.getResponseElement().getContent() != null && response.getResponseElement().getContent().size() > 0) {
                        List<ListStore> content = response.getResponseElement().getContent();
                        loadMoreDelegate.addAllItem(items,content);

                        if (response.getResponseElement().getLast()) {
                            loadMoreDelegate.setStatusNoMore();
                        } else {
                            loadMoreDelegate.setStatusNormal();
                        }
                    }
                }
                multiAdapter.notifyDataSetChanged();
            }
        });
    }
}
